﻿using MyBot.Api;
using MyBot.Models.MessageModels;
using QQRobot.AMiao.Help;
using QQRobot.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using WebApiClient;

namespace QQRobot.AMiao.Instructions
{
    public class Command
    {
        /// <summary>
        /// 群消息命令执行
        /// </summary>
        public static async Task GroupCommandImplement(ChatMessage chatMessage,
            QQChannelApi qChannelApi)
        {
            var msgId = chatMessage.Id; //消息ID
            var groupId = chatMessage.GroupOpenId; //群聊消息发送者的OpenId
            var content = chatMessage.Content;//消息内容
            var openId = chatMessage.Author.UserOpenId; //群聊消息发送者的OpenId
            var msg = qChannelApi.GetChatMessageApi();

            //百度热搜
            if (content.Contains(CommandType.BaiduHotSearch.GetDescription()))
            {
                var baiduHot = await BaiduAPI.GetBaiduHotSearchAsync();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("百度热搜榜单");
                baiduHot?.Data?.Cards?.FirstOrDefault()?.Content.Take(10).ToList().ForEach(x =>
                {
                    if (x.Query.Contains("习近平") || x.Query.Contains("习大大") || x.Query.Contains("主席"))
                        return;
                    stringBuilder.AppendLine($"{x.Index + 1}. {x.Query}");
                });
                var media = await msg.SendGroupMediaAsync(
                                     groupId,
                                     mediaType: ChatMediaType.Image,
                                     "https://fyb-pc-static.cdn.bcebos.com/static/asset/homepage@2x_daaf4f0f6cf971ed6d9329b30afdf438.png",
                                     false
                                     );

                await msg.SendGroupMessageAsync(
                           groupId,
                           stringBuilder.ToString(),
                           msgType: ChatMessageType.Media,
                           media: new ChatMessageMedia { FileInfo = media.FileInfo },
                           passiveMsgId: msgId
                           );
            }
            else if (content.Contains(CommandType.BaiduTranslate.GetDescription()))
            {
                content = StrHelp.RemoveStr(content, CommandType.BaiduTranslate.GetDescription());
                var translates = await BaiduAPI.GetBaiduTranslateAsync(content);
                var tran = translates.trans_result.FirstOrDefault();
                if (tran == null)
                {
                    await msg.SendGroupMessageAsync(
                                   groupId,
                                     $"不好意思，您的机器人思路有点乱，请稍后重试",
                                   msgType: ChatMessageType.Text,
                                   passiveMsgId: msgId
                                   );
                }
                else
                {
                    await msg.SendGroupMessageAsync(
                                   groupId,
                                   tran.dst,
                                   msgType: ChatMessageType.Text,
                                   passiveMsgId: msgId
                                   );
                }
            }
            else if (content.Contains(CommandType.AIDialogueDrawing.GetDescription()))
            {
                content = StrHelp.RemoveStr(content, CommandType.AIDialogueDrawing.GetDescription());
                var translates = await BaiduAPI.GetBaiduTranslateAsync(content);
                var tran = translates.trans_result.FirstOrDefault();
                if (tran == null)
                {
                    await msg.SendGroupMessageAsync(
                                   groupId,
                                     $"不好意思，您的机器人思路有点乱，请稍后重试",
                                   msgType: ChatMessageType.Text,

                                   //markdown: new MessageMarkdown { Content = "点击这里访问 [链接](https://www.example.com)" },
                                   passiveMsgId: msgId
                                   );
                }
                else
                {
                    content = tran.dst;
                }
                var img = await SiliconFlowAPI.GetImgGenerationsAsync(new Services.Models.Request.ImgGenerationsRequest
                {
                    prompt = content
                });
                if (img != null)
                {
                    var media = await msg.SendGroupMediaAsync(
                       groupId,
                       mediaType: ChatMediaType.Image,
                       img?.images?.FirstOrDefault().url,
                       false
                       );
                    await msg.SendGroupMessageAsync(
                              groupId,
                                $"生成成功，请查收",
                              msgType: ChatMessageType.Media,
                              media: new ChatMessageMedia { FileInfo = media.FileInfo },
                              //markdown: new MessageMarkdown { Content = "点击这里访问 [链接](https://www.example.com)" },
                              passiveMsgId: msgId
                              );
                }
                else
                {
                    await msg.SendGroupMessageAsync(
                                 groupId,
                                   $"不好意思，您的机器人思路有点乱，请稍后重试",
                                 msgType: ChatMessageType.Text,

                                 //markdown: new MessageMarkdown { Content = "点击这里访问 [链接](https://www.example.com)" },
                                 passiveMsgId: msgId
                                 );
                }
            }
            else if (content.Contains(CommandType.BigLotto.GetDescription()))
            {
                var api = HttpApi.Create<ILotteryAPI>();
                string url = "https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=10&isVerify=1&pageNo=1";
                if (content.Contains("PC"))
                {
                    url = "https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=15&isVerify=1&pageNo=1";
                }
                var bigLottoResult = await api.GeBigLottoAsync(url);
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine();
                if (content.Contains("PC"))
                {
                    stringBuilder.AppendLine($"期号\t\t开奖日期\t\t开奖号码\t\t\t\t一等奖金额\t中奖注数");
                }
                else
                {
                    stringBuilder.AppendLine($"期号\t\t开奖号码");
                }
                if (bigLottoResult != null && bigLottoResult.ErrorCode == "0"
                    && bigLottoResult.Value.List?.Any() == true)
                {
                    var current = false;
                    bigLottoResult.Value.List.ForEach(s =>
                    {
                        if (!current) stringBuilder.AppendLine();
                        if (content.Contains("PC"))
                        {
                            var one = s.PrizeLevelList.FirstOrDefault(x => x.AwardType == 0);//一等奖信息
                            if (one != null)
                            {
                              
                                stringBuilder.AppendFormat($"{s.LotteryDrawNum}\t{s.LotteryDrawTime}\t{s.LotteryDrawResult}\t{one.StakeAmount}元\t    {one.StakeCount}\n");
                                
                            }
                           
                        }
                        else
                        {
                            stringBuilder.AppendFormat($"{s.LotteryDrawNum}\t{s.LotteryDrawResult}\n");
                        }
                        if (!current) stringBuilder.AppendLine();
                        current = true;
                    });
                    var media = await msg.SendGroupMediaAsync(
                                  groupId,
                                  mediaType: ChatMediaType.Image,
                                  //"http://t15.baidu.com/it/u=4166817967,3811486590&fm=224&app=112&f=JPEG?w=500&h=500",
                                  "https://static.sporttery.cn/res_1_0/tcw/upload/202010/11232925tzyq.jpg",
                                  false
                                  );

                    await msg.SendGroupMessageAsync(
                               groupId,
                               stringBuilder.ToString(),
                               msgType: ChatMessageType.Media,
                               media: new ChatMessageMedia { FileInfo = media.FileInfo },
                               passiveMsgId: msgId
                               );
                }
                else
                {
                    await msg.SendGroupMessageAsync(
                                 groupId,
                                   $"不好意思，您的机器人思路有点乱，请稍后重试",
                                 msgType: ChatMessageType.Text,

                                 //markdown: new MessageMarkdown { Content = "点击这里访问 [链接](https://www.example.com)" },
                                 passiveMsgId: msgId
                                 );
                }


            }
            else if (content.Contains(CommandType.UnionLotto.GetDescription()))
            {
                string url = "https://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueCount=&issueStart=&issueEnd=&dayStart=&dayEnd=&pageNo=1&pageSize=10&week=&systemType=PC";
                if (content.Contains("PC"))
                {
                    url = "https://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueCount=&issueStart=&issueEnd=&dayStart=&dayEnd=&pageNo=1&pageSize=15&week=&systemType=PC";
                }
                var api = HttpApi.Create<ILotteryAPI>();
                var unionLottoResult = await api.GetUnionLottoAsync(url);
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine();
                if (content.Contains("PC"))
                {
                    stringBuilder.AppendLine($"期号\t\t开奖日期\t\t\t开奖号码\t\t\t\t一等奖金额\t中奖注数");
                }
                else
                {
                    stringBuilder.AppendLine($"期号\t\t开奖号码");
                }

                if (unionLottoResult != null && unionLottoResult.State == 0 && unionLottoResult.Result?.Any() == true)
                {
                    var current = false;
                    unionLottoResult.Result.ForEach(s =>
                    {
                        if (!current) stringBuilder.AppendLine();
                        if (content.Contains("PC"))
                        {
                            var one = s.PrizeGrades.FirstOrDefault(x => x.Type == 1);//一等奖信息
                            if (one != null)
                            {
                                stringBuilder.AppendFormat($"{s.Code}\t{s.Date}\t{s.Red}+{s.Blue}\t{one.TypeMoney}元\t   {one.TypeNum}\n");
                            }
                        }
                        else
                        {
                            stringBuilder.AppendFormat($"{s.Code}\t{s.Red}+{s.Blue}\n");
                        }
                        if (!current) stringBuilder.AppendLine();
                        current = true;
                    });

                    var media = await msg.SendGroupMediaAsync(
                                groupId,
                                mediaType: ChatMediaType.Image,
                                "https://img2.baidu.com/it/u=461152136,2760563774&fm=253&fmt=auto&app=138&f=PNG?w=840&h=354",
                                false
                                );

                    await msg.SendGroupMessageAsync(
                               groupId,
                               stringBuilder.ToString(),
                               msgType: ChatMessageType.Media,
                               media: new ChatMessageMedia { FileInfo = media.FileInfo },
                               passiveMsgId: msgId
                               );
                }
                else
                {
                    await msg.SendGroupMessageAsync(
                                 groupId,
                                   $"不好意思，您的机器人思路有点乱，请稍后重试",
                                 msgType: ChatMessageType.Text,

                                 //markdown: new MessageMarkdown { Content = "点击这里访问 [链接](https://www.example.com)" },
                                 passiveMsgId: msgId
                                 );
                }
            }

            else
            {
                var media = await msg.SendGroupMediaAsync(
                            groupId,
                            mediaType: ChatMediaType.Image,
                            "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png",
                            false
                            );

                await msg.SendGroupMessageAsync(
                 groupId,
                         $"收到消息啦！您发送的消息为 ->{content}",
                 msgType: ChatMessageType.Media,
                 media: new ChatMessageMedia
                 {
                     FileInfo = media.FileInfo
                 },
                         passiveMsgId: msgId
                         );
            }
        }

    }
}
